﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace Weazel.Willows.Model
{
	/// <summary>
	/// This class represents an alias type. An alias type maps from one type to another. 
	/// This is heavily used inside "compound types".
	/// </summary>
	public class AliasType : BasicType
	{
		/// <summary>
		/// variable to temporarily hold the referenced type name
		/// </summary> 
		private string originalTypeName;

		/// <summary>
		/// Reference to the actual type. Only valid after "resolve".
		/// </summary>
		private BasicType originalType;
		public BasicType OriginalType
		{
			get { return originalType; }
		}

		public AliasType(TypeRegistry registry, BasicType originalType, string name)
			: base(registry, name)
		{
			this.originalType = originalType;
			this.Resolved = true;
		}

		public AliasType(TypeRegistry registry)
			: base(registry, null)
		{
			this.originalType = null;
		}

		public override void Resolve()
		{
			System.Diagnostics.Debug.Assert(!Resolved);
			originalType = Registry[originalTypeName];
			Resolved = true;
		}

		public override int BitWidth
		{
			get { return originalType.BitWidth; }
		}

		public override bool IsSimpleType
		{
			get { return originalType.IsSimpleType; }
		}

		public void Read(XmlElement description)
		{
			System.Diagnostics.Debug.Assert(description.Name == "TypeDef");

			System.Diagnostics.Debug.Assert(description.HasAttribute("Name"));
			System.Diagnostics.Debug.Assert(description.HasAttribute("Type"));

			this.Name = description.Attributes["Name"].Value;
			this.originalTypeName = description.Attributes["Type"].Value;
		}

		/// <summary>
		/// n/a
		/// </summary>
		/// <returns>string representation of this alias type</returns>
		public override string ToString()
		{
			return Name + " : " + originalType.ToString();
		}
	}
}
